﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.IO;
using System.Xml;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Utils
{
  /// <summary>
        /// FileDirectoryUtility 类,方法不包含异常处理
        /// </summary>
        public class FileDirectoryUtility
        {
            /// <summary>
            /// 路径分割符
            /// </summary>
            private const string PATH_SPLIT_CHAR = "\\";

            /// <summary>
            /// 构造函数
            /// </summary>
            private FileDirectoryUtility()
            {
            }        

            /// <summary>
            /// 复制指定目录的所有文件,不包含子目录及子目录中的文件
            /// </summary>
            /// <param name="sourceDir">原始目录</param>
            /// <param name="targetDir">目标目录</param>
            /// <param name="overWrite">如果为true,表示覆盖同名文件,否则不覆盖</param>
            public static void CopyFiles(string sourceDir, string targetDir, bool overWrite)
            {
                CopyFiles(sourceDir, targetDir, overWrite, false);
            }

            /// <summary>
            /// 复制指定目录的所有文件
            /// </summary>
            /// <param name="sourceDir">原始目录</param>
            /// <param name="targetDir">目标目录</param>
            /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
            /// <param name="copySubDir">如果为true,包含目录,否则不包含</param>
            public static void CopyFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir)
            {
                //复制当前目录文件
                foreach (string sourceFileName in Directory.GetFiles(sourceDir))
                {
                    string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));

                    if (File.Exists(targetFileName))
                    {
                        if (overWrite == true)
                        {
                            File.SetAttributes(targetFileName, FileAttributes.Normal);
                            File.Copy(sourceFileName, targetFileName, overWrite);
                        }
                    }
                    else
                    {
                        File.Copy(sourceFileName, targetFileName, overWrite);
                    }
                }
                //复制子目录
                if (copySubDir)
                {
                    foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
                    {
                        string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                        if (!Directory.Exists(targetSubDir))
                            Directory.CreateDirectory(targetSubDir);
                        CopyFiles(sourceSubDir, targetSubDir, overWrite, true);
                    }
                }
            }

            /// <summary>
            /// 剪切指定目录的所有文件,不包含子目录
            /// </summary>
            /// <param name="sourceDir">原始目录</param>
            /// <param name="targetDir">目标目录</param>
            /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
            public static void MoveFiles(string sourceDir, string targetDir, bool overWrite)
            {
                MoveFiles(sourceDir, targetDir, overWrite, false);
            }

            /// <summary>
            /// 剪切指定目录的所有文件
            /// </summary>
            /// <param name="sourceDir">原始目录</param>
            /// <param name="targetDir">目标目录</param>
            /// <param name="overWrite">如果为true,覆盖同名文件,否则不覆盖</param>
            /// <param name="moveSubDir">如果为true,包含目录,否则不包含</param>
            public static void MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir)
            {
                //移动当前目录文件
                foreach (string sourceFileName in Directory.GetFiles(sourceDir))
                {
                    string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                    if (File.Exists(targetFileName))
                    {
                        if (overWrite == true)
                        {
                            File.SetAttributes(targetFileName, FileAttributes.Normal);
                            File.Delete(targetFileName);
                            File.Move(sourceFileName, targetFileName);
                        }
                    }
                    else
                    {
                        File.Move(sourceFileName, targetFileName);
                    }
                }
                if (moveSubDir)
                {
                    foreach (string sourceSubDir in Directory.GetDirectories(sourceDir))
                    {
                        string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                        if (!Directory.Exists(targetSubDir))
                            Directory.CreateDirectory(targetSubDir);
                        MoveFiles(sourceSubDir, targetSubDir, overWrite, true);
                        Directory.Delete(sourceSubDir);
                    }
                }
            }

            /// <summary>
            /// 删除指定目录的所有文件，不包含子目录
            /// </summary>
            /// <param name="targetDir">操作目录</param>
            public static void DeleteFiles(string targetDir)
            {
                DeleteFiles(targetDir, false);
            }

            /// <summary>
            /// 删除指定目录的所有文件和子目录
            /// </summary>
            /// <param name="targetDir">操作目录</param>
            /// <param name="delSubDir">如果为true,包含对子目录的操作</param>
            public static void DeleteFiles(string targetDir, bool delSubDir)
            {
                if (Directory.Exists(targetDir))
                {
                    foreach (string fileName in Directory.GetFiles(targetDir))
                    {
                        if (File.Exists(fileName))
                        {
                            File.SetAttributes(fileName, FileAttributes.Normal);
                            File.Delete(fileName);
                        }
                    }
                    if (delSubDir)
                    {
                        DirectoryInfo dir = new DirectoryInfo(targetDir);
                        foreach (DirectoryInfo subDi in dir.GetDirectories())
                        {
                            DeleteFiles(subDi.FullName, true);
                            subDi.Delete();
                        }
                    }
                }
            }

            /// <summary>
            /// 创建指定目录
            /// </summary>
            /// <param name="targetDir"></param>
            public static void CreateDirectory(string targetDir)
            {
                DirectoryInfo dir = new DirectoryInfo(targetDir);
                if (!dir.Exists)
                    dir.Create();
            }

            /// <summary>
            /// 建立子目录
            /// </summary>
            /// <param name="targetDir">目录路径</param>
            /// <param name="subDirName">子目录名称</param>
            public static void CreateDirectory(string parentDir, string subDirName)
            {
                CreateDirectory(parentDir + PATH_SPLIT_CHAR + subDirName);
            }

            /// <summary>
            /// 删除指定目录
            /// </summary>
            /// <param name="targetDir">目录路径</param>
            public static void DeleteDirectory(string targetDir)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(targetDir);
                if (dirInfo.Exists)
                {
                    DeleteFiles(targetDir, true);
                    dirInfo.Delete(true);
                }
            }

            /// <summary>
            /// 删除指定目录的所有子目录,不包括对当前目录文件的删除
            /// </summary>
            /// <param name="targetDir">目录路径</param>
            public static void DeleteSubDirectory(string targetDir)
            {
                foreach (string subDir in Directory.GetDirectories(targetDir))
                {
                    DeleteDirectory(subDir);
                }
            }


            /// <summary>
          /// 从指定的目录下，递归搜索txt文件
          /// </summary>
          /// <param name="dllPath">文件所在的路径</param>
          /// <returns>包含绝对路径的d文件集合</returns>
          public static IList<string> GetAllTxtFileFromDir(DirectoryInfo directory)
          {
              IList<string> result = new List<string>();        
             
             
             DirectoryInfo[] subDirectories = directory.GetDirectories();
             
             foreach (DirectoryInfo subDirectory in subDirectories)
             {
                 foreach (FileInfo file in subDirectory.GetFiles("*.txt"))  //*.txt  改为*.*
                 {
                     result.Add(file.FullName);
                 }
             }
             
             return result;
         }

          public static bool CreatTxt(Page page,DataTable dt, string fileName)
          {
              bool flag = true;
              try
              {
                  string path = System.Web.HttpContext.Current.Server.MapPath("~/log/" + fileName);
                 // if (System.IO.File.Exists(path)) System.IO.File.Delete(path);

                  if (File.Exists(path))
                  {
                      File.Delete(path);
                  }
                  int rows = dt.Rows.Count;
                  if (dt.Rows.Count < 1)
                      return false;
                  if (!File.Exists(path))
                  {
                      File.Create(path).Close();
                  }

                  FileStream fsobj = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                  StreamWriter _sw = new StreamWriter(fsobj, System.Text.Encoding.GetEncoding("GB2312"));

                 
 

                      for (int i = 0; i < rows; i++)
                      {
                          StringBuilder stringBuffer = new StringBuilder();
                          int j = 0;
                          foreach (DataColumn col in dt.Columns)
                          {
                              j++;
                              stringBuffer.Append(dt.Rows[i][col.ColumnName].ToString());
                              if (j < dt.Columns.Count)
                                  stringBuffer.Append("\t");
                          }
                          stringBuffer.Append("\r\n");
                          _sw.Write(stringBuffer.ToString());
                      }



                  _sw.Close();

                  fsobj.Close();
                  ReadFile(page, path);
                  page.Response.End();//结束
              }
              catch
              {
                  flag = false;
              }
              return flag;
          }
          public static void ReadFile(Page page, string destFileName)
          {
              if (File.Exists(destFileName))
              {
                  FileInfo fi = new FileInfo(destFileName);
                  page.Response.Clear();
                  page.Response.ClearHeaders();
                  page.Response.Buffer = false;

                  page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
                  page.Response.AppendHeader("Content-Length", fi.Length.ToString());
                  page.Response.ContentType = "text/plain";//定义输出流类型
                  page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                  page.Response.WriteFile(destFileName);
                  page.Response.Flush();
                  page.Response.End();
              }
              else
              {
                  page.Response.Write("<script langauge=javascript>alert('文件不存在!');history.go(-1);</script>");
                  page.Response.End();
              }
          }
            /// <summary>
            /// 将指定目录下的子目录和文件生成xml文档
            /// </summary>
            /// <param name="targetDir">根目录</param>
            /// <returns>返回XmlDocument对象</returns>
            public static XmlDocument CreateXml(string targetDir)
            {
                XmlDocument myDocument = new XmlDocument();
                XmlDeclaration declaration = myDocument.CreateXmlDeclaration("1.0", "utf-8", null);
                myDocument.AppendChild(declaration);
                XmlElement rootElement = myDocument.CreateElement(targetDir.Substring(targetDir.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                myDocument.AppendChild(rootElement);
                foreach (string fileName in Directory.GetFiles(targetDir))
                {
                    XmlElement childElement = myDocument.CreateElement("File");
                    childElement.InnerText = fileName.Substring(fileName.LastIndexOf(PATH_SPLIT_CHAR) + 1);
                    rootElement.AppendChild(childElement);
                }
                foreach (string directory in Directory.GetDirectories(targetDir))
                {
                    XmlElement childElement = myDocument.CreateElement("Directory");
                    childElement.SetAttribute("Name", directory.Substring(directory.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                    rootElement.AppendChild(childElement);
                    CreateBranch(directory, childElement, myDocument);
                }
                return myDocument;
            }

            /// <summary>
            /// 生成Xml分支
            /// </summary>
            /// <param name="targetDir">子目录</param>
            /// <param name="xmlNode">父目录XmlDocument</param>
            /// <param name="myDocument">XmlDocument对象</param>
            private static void CreateBranch(string targetDir, XmlElement xmlNode, XmlDocument myDocument)
            {
                foreach (string fileName in Directory.GetFiles(targetDir))
                {
                    XmlElement childElement = myDocument.CreateElement("File");
                    childElement.InnerText = fileName.Substring(fileName.LastIndexOf(PATH_SPLIT_CHAR) + 1);
                    xmlNode.AppendChild(childElement);
                }
                foreach (string directory in Directory.GetDirectories(targetDir))
                {
                    XmlElement childElement = myDocument.CreateElement("Directory");
                    childElement.SetAttribute("Name", directory.Substring(directory.LastIndexOf(PATH_SPLIT_CHAR) + 1));
                    xmlNode.AppendChild(childElement);
                    CreateBranch(directory, childElement, myDocument);
                }
            }
        }

   
}
